<template>
  <div style="padding: 10px" :class="activeKey == 1 ? 'look-box' : ''">
    <a-tabs
      style="background: #ffff; height: 100%"
      v-model:activeKey="activeKey"
      @change="changeViewType"
    >
      <a-tab-pane key="1" tab="销售看板">
        <div class="look-view">
          <a-form layout="vertical" style="margin-top: 10px">
            <a-row :gutter="8">
              <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                <a-form-item>
                  <a-input
                    v-model:value="searchParams.name"
                    placeholder="请输入计划名称"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                <a-form-item>
                  <div
                    class="w-100p select-member"
                    @click="chooseMemberVisible = true"
                  >
                      <span
                        v-if="searchParams.execute_uids.length"
                        class="have-select"
                      >
                        已选择
                        <span class="text-blue">{{
                            searchParams.execute_uids.length
                          }}</span>
                        位成员
                      </span>
                    <span v-else> 选择执行人员 </span>
                  </div>
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                <a-form-item>
                  <a-select
                    class="w-100p"
                    v-model:value="searchParams.target_type"
                    placeholder="请选择目标类型"
                    allowClear
                    :options="typeList"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                <a-form-item>
                  <a-date-picker
                    class="w-100p"
                    v-model:value="searchParams.plan_start"
                    placeholder="请选择开始时间"
                    :valueFormat="dateFormatStr"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                <a-form-item>
                  <a-date-picker
                    class="w-100p"
                    v-model:value="searchParams.plan_end"
                    placeholder="请选择结束时间"
                    :valueFormat="dateFormatStr"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                <a-form-item label="">
                  <a-space>
                    <a-button @click="reset">重置</a-button>
                    <a-button type="primary" @click.stop="getViewList">
                      查询
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>

          <div class="view-list">
            <a-list
              v-for="(viewType, typeIndex) in viewData"
              :data-source="viewType.list"
              :key="typeIndex"
              :split="false"
              :loading="viewLoading"
              class="view-list-one"
            >
              <template #header>
                <div class="view-list-one-title">
                  {{viewType.status_txt}}({{viewType?.list?.length || 0}})
                </div>
              </template>
              <template #renderItem="{ item }">
                <a-list-item
                  class="list-box list-box-sub"
                >
                  <a-card size="small" style="width: 100%">
                    <template #title>
                      <span>
                        {{item.name}}
                      </span>
                    </template>
                    <div class="view-content-box">
                      <p>计划时间：{{item.plan_start}} ~ {{item.plan_end}}</p>
                      <p>执行人员： {{item?.execute_unames?.join("，")}}</p>
                      <p>计划目标：{{item.target_type_txt}}</p>
                      <p>计划/完成{{item.target_type == 4 ? '金额' : '数量'}}：{{item.target_num}}/{{item.complete_num || 0}}</p>
                      <div class="rate-box">
                        <span style="font-size: 14px">{{item.target_num && item.complete_num ? item.complete_num < item.target_num ? parseRatio(((Number(item.complete_num) / Number(item.target_num)) * 100
                        )) + '%' : '100%' : '0%'}}</span>
                        <span style="font-size: 12px">完成率</span>
                      </div>
                    </div>
                  </a-card>
                </a-list-item>
              </template>
            </a-list>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="销售计划">
        <div class="header-box">
          <div class="header">
            <a-row type="flex" align="middle" justify="center">
              <template v-for="(basic, basicIndex) in basicData" :key="basicIndex">
                <a-divider
                  type="vertical"
                  style="height: 20px; background-color: #7cb305"
                  v-if="basicIndex > 0"
                />
                <a-col :flex="1" style="text-align: center" class="header-content">
                  <div class="num-info">
                    {{ basic.num }}
                  </div>
                  <div>
                    {{basic.title}}
                    <text-tip
                      v-if="basic.tips"
                      :tips="basic.tips"
                    ></text-tip>
                  </div>
                </a-col>
              </template>
            </a-row>
          </div>
        </div>

        <a-table
          :dataSource="dataList"
          :columns="columns"
          :loading="loading"
          rowKey="id"
          :scroll="{ x: 'max-content', y: $store.getters.isMobile ? 550 : true }"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #title>
            <div class="flex justify-between header-plan">
              <div class="flex-1">
                <a-form layout="vertical">
                  <a-row :gutter="8" :wrap="true" type="flex">
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item>
                        <a-input
                          v-model:value="searchParams.name"
                          placeholder="请输入计划标题"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item>
                        <div
                          class="w-100p select-member"
                          @click="chooseMemberVisible = true"
                        >
                      <span
                        v-if="searchParams.execute_uids.length"
                        class="have-select"
                      >
                        已选择
                        <span class="text-blue">{{
                            searchParams.execute_uids.length
                          }}</span>
                        位成员
                      </span>
                          <span v-else> 选择执行人员 </span>
                        </div>
                      </a-form-item>
                    </a-col>
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item>
                        <a-select
                          class="w-100p"
                          v-model:value="searchParams.complete_status"
                          placeholder="请选择完成状态"
                          allowClear
                          :options="completeStatusList"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item>
                        <a-select
                          class="w-100p"
                          v-model:value="searchParams.status"
                          placeholder="请选择计划状态"
                          allowClear
                          :options="statusList"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item>
                        <a-date-picker
                          class="w-100p"
                          v-model:value="searchParams.plan_start"
                          placeholder="请选择开始时间"
                          :valueFormat="dateFormatStr"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item>
                        <a-date-picker
                          class="w-100p"
                          v-model:value="searchParams.plan_end"
                          placeholder="请选择结束时间"
                          :valueFormat="dateFormatStr"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                      <a-form-item label="">
                        <a-space>
                          <a-button @click="reset">重置</a-button>
                          <a-button type="primary" @click="getDataList(true)">
                            搜索
                          </a-button>
                        </a-space>
                      </a-form-item>
                    </a-col>
                    <a-col style="margin-left: auto">
                      <a-button
                        type="primary"
                        @click="addPlan"
                        v-permission="['businessPLan', 'curd', 'add']"
                      >
                        新建招商计划
                      </a-button>
                    </a-col>
                  </a-row>
                </a-form>
              </div>
            </div>
          </template>

          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'target_type'">
              <a-tag
                :color="text == 1 ? '#5ac61d' : text == 2 ? '#1890ff' : '#fe8122'"
              >
                {{ record.target_type_txt }}
              </a-tag>
            </template>
            <template v-if="column.key === 'target_num'">
              <span>{{text}}{{record?.target_type == 4 ? '元' : '个'}}</span>
            </template>
            <template v-if="column.key === 'complete_num'">
              <div class="status">
                <div :style="{ fontWeight: 'bold' }">
                  {{ `${text || 0}/${record.target_num}` }}
                </div>
                <div
                  v-if="timeIsAfter(record.plan_end) || text >= record.target_num"
                >
              <span v-if="text >= record.target_num" class="green">
                （已完成）
              </span>
                  <span v-else class="red"> （未完成） </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag :color="text == 1 ? 'green' : 'red'">
                {{ text == 1 ? "启用" : "停用" }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button
                v-permission="['businessPLan', 'curd', 'edit']"
                type="link"
                @click="editPlan(text)"
              >编辑</a-button
              >
              <a-button
                v-permission="['businessPLan', 'curd', 'detail']"
                type="link"
                @click="completePlan(text, record)"
              >完成情况</a-button
              >
              <a-button
                v-permission="['businessPLan', 'curd', 'delete']"
                type="link"
                @click="deletePlan(text)"
                danger
              >删除</a-button
              >
            </template>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>


    <!--  选择人员  -->
    <ChooseOrgMember
      :visible="chooseMemberVisible"
      :getDetail="true"
      :deptDisabled="true"
      @request="$utils.commonRequest"
      @close="closeChooseMemberModal"
      @success="handleMemberSelect"
      :checkedList="idList"
    />

    <!--  新建/编辑招商计划  -->
    <AddPlan
      :visible="addVisible"
      :editId="editId"
      @cancel="addVisible = false"
      @success="success"
    />

    <!--  完成情况  -->
    <CompletePlan
      :visible="completeVisible"
      :editId="editId"
      :targetType="targetType"
      @cancel="completeVisible = false"
    />
  </div>
</template>
<script>
import {
  defineComponent,
  ref,
  createVNode,
  reactive,
  computed,
  watch,
  toRefs,
} from "vue";
import {ExclamationCircleOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { Form, message, Statistic } from "ant-design-vue";
import request from "../../../common/utils/request";
import { Modal } from "ant-design-vue";
import moment from "moment";
import store from "../../../store";
const dateFormatStr = "YYYY-MM-DD";
const useForm = Form.useForm;
import AddPlan from "@/views/village/AttractPlan/modules/addPlan.vue";
import { ChooseOrgMember } from "bl-common-vue3";
import CompletePlan from "@/views/village/AttractPlan/modules/completePlan.vue";
import { PLAN_TYPE_OPTIONS } from "@/views/village/AttractPlan/constant";
import { TextTip } from "bl-common-vue3";

export default defineComponent({
  name: "attractPlan",
  components: {
    QuestionCircleOutlined,
    CompletePlan,
    ChooseOrgMember,
    PlusOutlined,
    Statistic,
    AddPlan,
    TextTip,
  },
  setup() {
    // search
    const searchParams = reactive({
      name: "",
      complete_status: undefined,
      status: undefined,
      plan_start: undefined,
      plan_end: undefined,
      execute_uids: [],
      target_type: undefined,
    });

    const state = reactive({
      statusList: STATUS_OPTIONS,
      completeStatusList: COMPLETE_STATUS_OPTIONS,
      typeList: PLAN_TYPE_OPTIONS,
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      addVisible: false,
      chooseMemberVisible: false,
      idList: {},
      editId: undefined,
      completeVisible: false,
      loading: false,
      targetType: undefined,
      activeKey: '1',
      basicData: [
        {
          title: '总计划数量',
          tips: '',
          num: 0,
        },
        {
          title: '已完成',
          tips: '',
          num: 0,
        },
        {
          title: '未完成',
          tips: '',
          num: 0,
        },
        {
          title: '进行中',
          tips: '',
          num: 0,
        },
        {
          title: '计划完成率',
          tips: '计划完成率=已完成/当前计划总数',
          num: 0,
        },
      ],
      viewData: [],
      viewLoading: false,
    });
    const { resetFields } = useForm(searchParams, {});

    // 销售看板数据
    const getViewList = () => {
      const params = {};
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      state.viewLoading = true;
      request
        .post("/org", "/business/plan/boardList", params)
        .then((res) => {
          state.viewData = res?.list || [];
        })
        .finally(() => {
          state.viewLoading = false;
        });
    };

    const reset = () => {
      resetFields();
      state.idList = {};
      state.targetType = undefined;
      if (state.activeKey == 2) {
        getDataList(true);
      } else {
        getViewList();
      }
    };

    const parseRatio = (number, decimal = 2) => {
      return (Math.floor(number * 100) / 100).toFixed(decimal);
    };

    const getDataList = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        limit: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request
        .post("/org", "/business/plan/list", params)
        .then((res) => {
          state.dataList = res.list;
          state.total = res.total;
          state.basicData[0].num = res.planNum;
          state.basicData[1].num = res.computeNum;
          state.basicData[2].num = res.incompleteNum;
          state.basicData[3].num = res.doNum;
          state.basicData[4].num = res.planNum && res.computeNum  ? parseRatio(
            ((Number(res.computeNum) / Number(res.planNum)) * 100
            )) + "%" : '0%';
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };
    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    // 新建招商计划
    const addPlan = () => {
      state.editId = undefined;
      state.addVisible = true;
    };

    const success = () => {
      getDataList(true);
      state.addVisible = false;
    };

    const closeChooseMemberModal = () => {
      state.chooseMemberVisible = false;
    };

    const handleMemberSelect = (data) => {
      state.idList = data;
      closeChooseMemberModal();
      searchParams.execute_uids = [];
      let users = data.user || [];
      if (users.length) {
        users.forEach((a) => {
          searchParams.execute_uids.push(a.uid);
        });
      } else {
        searchParams.execute_uids = [];
      }
      // console.log(data.user, '选择的人员9999');
    };

    //删除
    const deletePlan = (id) => {
      Modal.confirm({
        title: "确认删除该招商计划吗？",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request.del("/org", "/business/plan/del", { id: id }).then((res) => {
            message.success(res.msg || "删除成功！");
            state.page =
              state.dataList.length == 1 ? state.page - 1 : state.page;
            getDataList();
          });
        },
      });
    };

    // 编辑
    const editPlan = (id) => {
      state.editId = id;
      state.addVisible = true;
    };

    const completePlan = (id, record) => {
      state.editId = id;
      state.targetType = record?.target_type || undefined;
      state.completeVisible = true;
    };

    const timeIsAfter = (time) => {
      let now = moment();
      return now.isAfter(moment(time).add(1, "days"));
    };

    const init = () => {
      getDataList(true);
      getViewList();
    };

    const changeViewType = () => {
      reset();
    };

    init();

    const columns = [
      {
        title: "计划标题",
        align: "center",
        dataIndex: "name",
        key: "name",
        fixed: store.getters.isMobile ? undefined : "left",
      },
      {
        title: "计划执行日期",
        align: "center",
        width: 200,
        dataIndex: "plan_start",
        key: "plan_start",
        customRender: ({ text, record, index }) => {
          return record?.plan_start
            ? record?.plan_start + " 至 " + record?.plan_end
            : "--";
        },
      },
      {
        title: "执行人员",
        align: "center",
        dataIndex: "execute_unames",
        key: "execute_unames",
        customRender: ({ text, record, index }) => {
          return record?.execute_unames?.length
            ? record.execute_unames.join(" ")
            : "--";
        },
      },
      {
        title: "目标类型",
        dataIndex: "target_type",
        key: "target_type",
        align: "center",
      },
      {
        title: "目标数",
        dataIndex: "target_num",
        key: "target_num",
        align: "center",
      },
      {
        title: "当前进度",
        dataIndex: "complete_num",
        key: "complete_num",
        align: "center",
      },
      {
        title: "状态",
        dataIndex: "status",
        align: "center",
        key: "status",
      },
      {
        title: "操作",
        align: "center",
        dataIndex: "id",
        key: "action",
        width: 240,
        fixed: "right",
      },
    ];

    return {
      columns,
      searchParams,
      pagination,
      ...toRefs(state),
      dateFormatStr,
      reset,
      handleTableChange,
      addPlan,
      closeChooseMemberModal,
      success,
      handleMemberSelect,
      deletePlan,
      editPlan,
      completePlan,
      getDataList,
      timeIsAfter,
      changeViewType,
      parseRatio,
      getViewList,
    };
  },
});

const COMPLETE_STATUS_OPTIONS = [
  {
    value: 2,
    label: "已完成",
  },
  {
    value: 3,
    label: "未完成",
  },
];

const STATUS_OPTIONS = [
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "禁用",
  },
];
</script>

<style lang="less" scoped>
.header-plan {
  padding: 0 16px;
}
.a-col {
  position: relative;
  &::after {
    content: "";
    position: absolute;
    height: 50%;
    top: 25%;
    right: 0;
    width: 1px;
    background-color: #d9d9d9;
  }
}
.select-member {
  width: 100%;
  padding: 4px 7px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: #bfbfbf;
  cursor: pointer;
  .have-select {
    color: rgba(0, 0, 0, 0.65);
  }
  &:hover {
    border: 1px solid #52a5ff;
  }
}
.status {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.green {
  color: #60d455;
}
.red {
  color: #eb6563;
}
.header-box {
  background: #fff;
  padding: 14px 10px;
}
.header {
  background-color: rgb(240, 242, 245);
  padding: 16px 10px;

  .num-info {
    color: @primary-color;
    font-size: 30px;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: break-all;
  }
}
.header-content {
  width: 0;
}
.look-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px 16px;
}
.look-box {
  height: 100%;
}
:deep(.ant-tabs-content) {
  height: 100%;
}
.view-list {
  flex: 1;
  display: flex;
  overflow: hidden;
}
.view-list-one {
  flex: 1;
  width: 0;
  background: #ececec;
  border-radius: 8px;
  padding: 14px 0;
  display: flex;
  flex-direction: column;
  &:not(:last-child) {
    margin-right: 20px;
  }
}
.view-list-one-title {
  padding:0 14px;
  font-size: 18px;
  font-weight: bold;
  word-break: break-all;
}

.view-content-box {
  position: relative;
  p {
    &:last-of-type {
      margin-bottom: 0;
    }
  }
}

.rate-box {
  width: 56px;
  height: 56px;
  position: absolute;
  bottom: 0px;
  right: 10px;
  border-radius: 50%;
  border: 1px solid @primary-color;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: @primary-color;
}

:deep(.ant-spin-nested-loading) {
  overflow-y: auto;
  flex: 1;
  padding:0 14px;
  //height: calc(100% - 45px);
}

:deep(.ant-spin-nested-loading)::-webkit-scrollbar {
  width: 3px;
  height: 5px;
  background-color: #f5f5f5;
}

/*定义滚动条轨道圆角*/
:deep(.ant-spin-nested-loading)::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #ececec;
}

/*定义滑块 内阴影+圆角*/
:deep(.ant-spin-nested-loading)::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
  background-color: #dddddd;
}
:deep(.ant-table-title) {
  padding: 0;
}
</style>
